'use client';

import { useState } from 'react';
import { TripWithDetails } from '@/types/prisma';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { jsPDF } from 'jspdf';
import 'jspdf-autotable';

type PdfExportProps = {
  trip: TripWithDetails;
};

export function PdfExport({ trip }: PdfExportProps) {
  const [isExporting, setIsExporting] = useState(false);

  const handleExport = async () => {
    setIsExporting(true);
    try {
      const doc = new jsPDF();

      // 添加标题
      doc.setFont('helvetica', 'bold');
      doc.setFontSize(20);
      doc.text(trip.title, 20, 20);

      // 添加日期
      doc.setFontSize(12);
      doc.setFont('helvetica', 'normal');
      doc.text(
        `${format(trip.startDate, 'yyyy年MM月dd日', { locale: zhCN })} - ${format(
          trip.endDate,
          'yyyy年MM月dd日',
          { locale: zhCN }
        )}`,
        20,
        30
      );

      // 按日期分组活动
      const groupedActivities = trip.activities.reduce((groups, activity) => {
        const date = format(activity.date, 'yyyy-MM-dd');
        if (!groups[date]) {
          groups[date] = [];
        }
        groups[date].push(activity);
        return groups;
      }, {} as Record<string, typeof trip.activities>);

      let yPosition = 40;

      // 遍历每一天的活动
      Object.entries(groupedActivities).forEach(([date, activities]) => {
        // 添加日期标题
        doc.setFont('helvetica', 'bold');
        doc.text(
          format(new Date(date), 'MM月dd日 EEEE', { locale: zhCN }),
          20,
          yPosition
        );
        yPosition += 10;

        // 添加活动表格
        const tableData = activities.map((activity) => [
          format(activity.date, 'HH:mm'),
          activity.title,
          activity.description || '',
          activity.destination?.name || '',
        ]);

        doc.autoTable({
          startY: yPosition,
          head: [['时间', '活动', '描述', '地点']],
          body: tableData,
          margin: { left: 20 },
          styles: { fontSize: 10 },
        });

        yPosition = (doc as any).lastAutoTable.finalY + 10;

        // 如果页面空间不足，添加新页面
        if (yPosition > 250) {
          doc.addPage();
          yPosition = 20;
        }
      });

      // 保存PDF
      doc.save(`${trip.title}-行程.pdf`);
    } catch (error) {
      console.error('Failed to generate PDF:', error);
    } finally {
      setIsExporting(false);
    }
  };

  return (
    <button
      onClick={handleExport}
      disabled={isExporting}
      className="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50"
    >
      {isExporting ? '导出中...' : '导出为PDF'}
    </button>
  );
} 